<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    showFooter
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
    @cancel="cancelFn"
  >
    <!--    <BasicForm @register="registerForm">-->
    <!--    </BasicForm>-->
    <!--  :rules="rulesRef"  -->
    <Form
      :model="formData"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      label-align="right"
      ref="formRef"
    >
      <div v-for="(item, index) in formSchemaList">
        <FormItem
          v-bind="item"
          v-if="item.component"
          :name="item.field"
          v-show="(item.show != undefined && item.show) || item.show == undefined"
        >
          <Input
            v-if="item.component === 'Input'"
            :placeholder="'请输入' + item.label"
            v-model:value="formData[item.field]"
          ></Input>
          <InputNumber
            v-if="item.component === 'InputNumber'"
            :placeholder="item.placeholder ? item.placeholder : '请输入' + item.label"
            v-model:value="formData[item.field]"
          ></InputNumber>
          <FormSelectTable
            v-if="item.component === 'FormSelectTable'"
            v-bind="item"
            @success="tableSuccessFn"
            v-model:value="formData[item.field]"
          ></FormSelectTable>

          <div v-if="item.items" style="display: flex">
            <FormItem
              v-for="(item2, index2) in item.items"
              v-bind="item2"
              v-show="(item2.show != undefined && item2.show) || item2.show == undefined"
              :class="{ 'ant-col': true, 'ant-col-14': true, 'item-row': true }"
              :name="item2.field"
            >
              <SelectOrderIndex
                v-if="item2.component === 'SelectOrderIndex'"
                @onSubmitFn="orderSuccessFn"
                v-model:value="formData[item2.field]"
              ></SelectOrderIndex>
              <Switch
                v-if="item2.component === 'Switch'"
                :placeholder="item2.placeholder ? item2.placeholder : '请输入' + item2.label"
                v-model:checked="formData[item2.field]"
                @change="switchChangeFn"
              ></Switch>
              <Input
                v-if="item2.component === 'Input'"
                :placeholder="item2.placeholder ? item2.placeholder : '请输入' + item2.label"
                v-model:value="formData[item2.field]"
              ></Input>
              <InputNumber
                v-if="item2.component === 'InputNumber'"
                :placeholder="'请输入' + item2.label"
                v-model:value="formData[item2.field]"
                :name="item2.field"
              ></InputNumber>

              <Select
                v-if="item2.component === 'Select'"
                :placeholder="'请选择' + item2.label"
                v-model:value="formData[item2.field]"
                v-bind="item2.componentProps"
                @change="
                  (v, o) => {
                    return returnTypeChange(v, o, item2.field);
                  }
                "
              ></Select>

              <DatePicker
                v-if="item2.component === 'DatePicker'"
                :placeholder="'选择' + item2.label"
                v-model:value="formData[item2.field]"
                v-bind="item2.componentProps"
              ></DatePicker>
            </FormItem>
          </div>
        </FormItem>
      </div>
    </Form>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, h, toRaw } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema, rules } from './role.data';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { Form, FormItem, Input, InputNumber, DatePicker, Select, Switch } from 'ant-design-vue';

  import { BasicTree, TreeItem } from '@/components/Tree';
  import { addMouldApi, editMouldApi, detailMouldApi } from '@/api/sys/msUser';
  import SelectOrderIndex from '@/views/msManage/components/formSelectTable/order/SelectOrderIndex.vue';
  import FormSelectTable from '@/views/msManage/components/formSelectTable/index.vue';

  import { useMessage } from '@/hooks/web/useMessage';
  import util from '@/utils/util';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const { createMessage } = useMessage();
  const mouldMainId = ref('');

  const testObj = ref({ materialName: '123' });
  const formData = ref({});
  const labelCol = ref({ span: 3 });
  const wrapperCol = ref({ span: 18 });
  const formRef = ref();
  const rulesRef = ref({
    mouldNameObj: [{ required: true, message: '费用名称不能为空', trigger: 'change' }],
    materialNo: [
      { required: true, message: '物料编号不能为空', trigger: 'change' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    orderNo: [
      { required: true, message: '采购单号不能为空', trigger: 'change' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
  });

  const formSchemaRef = [...formSchema];
  const formSchemaList = ref(formSchemaRef);

  const formValue = ref({});

  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //打开弹层后的回调
    // resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;
    mouldMainId.value = '';
    if (unref(isUpdate)) {
      // console.log("---data.record:", data.record)
      mouldMainId.value = data.record.mouldMainId;
      let json = {
        mouldMainId: mouldMainId.value,
      };
      detailMouldApi(json).then((res) => {
        if (res.code == 200) {
          let item = res.data;
          let materialNosArr = [];
          if (item.items) {
            item.items.forEach((r) => {
              materialNosArr.push(r.mtid);
            });
          }
          item.isHandBoole = false;
          if (item.isHand == 1) {
            item.isHandBoole = true;
          }
          item.mouldNameObj = {
            name: item.model,
          };
          item.supplierObj = {
            supplierId: item.supplierId,
            supplierName: item.supplierName,
          };

          item.materialNos = materialNosArr.join(',');
          console.log('---item:', item);
          // if(!item.endDate){
          //   item.endDate="";
          // }
          formData.value = item;
          // setFieldsValue(item);
        } else {
          createMessage.error(res.message);
        }
      });
    } else {
      let item = {
        items: [],
        isHandBoole: false,
      };
      // formRef.value.resetFields(item);
      formData.value = item;
      //   setFieldsValue(item)
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增费用明细' : '编辑费用明细'));

  //async function handleSubmit()

  const handleSubmit = () => {
    try {
      // const values = await validate();
      formRef.value
        .validate()
        .then(() => {
          // console.log('values', formState, toRaw(formState));

          let values = toRaw(formData.value);

          setModalProps({ confirmLoading: true });
          // TODO custom api
          values.mouldMainId = mouldMainId.value;
          // console.log("---values::",values);
          // return;
          if (values.items) {
            let arr = [];
            values.items.forEach((r) => {
              arr.push(r.mtid);
            });

            values.materialNos = arr.join(',');
            delete values.items;
          }

          console.log('---values:', JSON.stringify(values));

          //保存
          if (!isUpdate.value) {
            addMouldApi(values).then((result) => {
              sunccFn(result);
            });
          } else {
            editMouldApi(values).then((result) => {
              sunccFn(result);
            });
          }
        })
        .catch((error) => {
          console.log('error', error);
        });
    } catch (e) {
      console.log(e);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };

  function sunccFn(result) {
    if (result && result.code == 200) {
      createMessage.success(result.message);
    } else {
      createMessage.error(result.message);
    }
    closeModal();
    emit('success');
  }

  function cancelFn() {
    formRef.value.clearValidate();
  }

  function orderSuccessFn(e) {
    let data = e.value;
    if (e.type == 'arr') {
      data = e.value[0];
      formData.value.mouldNameObj = {
        name: data.model,
      };
      formData.value.mouldName = data.model;
      formData.value.model = data.model;
      formData.value.materialName = data.materialName;
      formData.value.specification = data.specification;

      formData.value.supplierId = data.supplierId;
      formData.value.supplierName = data.supplierName;
      formData.value.materialNo = data.materialNo;
      formData.value.supplierObj = {
        supplierId: data.supplierId,
        supplierName: data.supplierName,
      };
      formData.value.price = data.orderPrice;
      formData.value.orderNo = data.orderNo;
      formData.value.startDate = data.orderDate;
      formData.value.userName = data.userName;

      if (data.remark && data.remark.indexOf('&') != -1) {
        let arr = data.remark.split('&');
        let type = null;
        let type_txt = arr[0];
        // switch (type_txt) {
        //   case "一次性":
        //     type = 1;
        //     break;
        //   case "累计":
        //     type = 2;
        //     break;
        //   case "不退还":
        //     type = 3;
        //     break;
        // }
        // 退款条件类别:  1一次性(数量) 2累计(数量) 3不退 4一次性(金额) 5累计(金额)
        if (
          (type_txt.indexOf('一次性') != -1 && type_txt.indexOf('数量') != -1) ||
          (type_txt.indexOf('一次性') != -1 && type_txt.indexOf('数量') == -1)
        ) {
          type = 1;
        }
        if (
          (type_txt.indexOf('累计') != -1 && type_txt.indexOf('数量') != -1) ||
          (type_txt.indexOf('累计') != -1 && type_txt.indexOf('数量') == -1)
        ) {
          type = 2;
        }
        if (type_txt.indexOf('一次性') != -1 && type_txt.indexOf('金额') != -1) {
          type = 4;
        }
        if (type_txt.indexOf('累计') != -1 && type_txt.indexOf('金额') != -1) {
          type = 5;
        }
        if (type_txt.indexOf('不退还') != -1) {
          type = 3;
        }
        formData.value.returnConditionType = type;
        formData.value.returnConditionNum = arr[1];
      }
    } else {
      formData.value.mouldNameObj = { materialName: data };
      formData.value.mouldName = data;
    }
    formRef.value.clearValidate();

    //console.log("---formValue.value::", formValue.value)
  }

  function tableSuccessFn(e) {
    formData.value.items = e;
  }

  function supplierSuccessFn(e) {
    formData.value.supplierObj = {
      supplierId: e.oid,
      supplierName: e.name,
    };
    formData.value.supplierId = e.oid;
    formData.value.supplierName = e.name;
    formRef.value.clearValidate();
  }
  function userSelectSuccessFn(e) {
    formData.value.userId = e.ids;
    formData.value.userName = e.names;
    formRef.value.clearValidate();
  }

  function switchChangeFn(field) {
    formData.value.isHand = field ? 1 : 0;
    if (field) {
      formSchemaList.value[0].items[1].show = false;
      formSchemaList.value[0].items[1].required = false;
      formSchemaList.value[0].items[2].show = true;
      formSchemaList.value[0].items[2].required = true;
    } else {
      formSchemaList.value[0].items[1].show = true;
      formSchemaList.value[0].items[1].required = true;
      formSchemaList.value[0].items[2].show = false;
      formSchemaList.value[0].items[2].required = false;
    }
    formData.value.mouldName = '';
    formData.value.mouldNameObj = null;
    console.log('----field:', field);
    console.log('----formData.value', formData.value);
  }

  function returnTypeChange(v, o, field) {
    //console.log(v,o,field);
    // 退款条件类别:  1一次性(数量) 2累计(数量) 3不退 4一次性(金额) 5累计(金额)
    if (field == 'returnConditionType') {
      for (let a = 0; a < formSchemaList.value.length; a++) {
        let r = formSchemaList.value[a];
        if (r.field == 'returnCondition') {
          let txt = '';
          let next = formSchemaList.value[a + 1];
          next.show = false;
          if (v == 1 || v == 2) {
            txt = '数量';
            if (v == 2) {
              next.show = true;
            }
          }
          if (v == 4 || v == 5) {
            txt = '金额';
          }
          r.items[1].label = `退款条件${txt}`;
        }
      }
    }
  }
</script>
<style lang="less">
  .item-row {
    margin: 0 auto;
    //padding-left: 5%;
    .ant-form-item-label {
      flex: 0 0 28.5%;
      max-width: 28.5%;
    }
  }

  .lqfp-8 {
    //padding-left: 9% !important;
  }
</style>
